﻿using Forum.Models;
using Forum.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Forum.Controllers
{
    public class HomeController : Controller
    {
        ForumDb db = new ForumDb();
        
        public ActionResult Index(string searchTerm= null)
        {
            //Get last 10 forum posts
            var latestForumPosts = db.ForumPosts
                .OrderByDescending(x => x.CreationTime)
                .Where(q => searchTerm == null || q.Title.StartsWith(searchTerm))
                .Take(10)
                .Select(x => new ForumPostViewModel
                {
                    Id= x.Id,
                    Title= x.Title,
                    CreationTime=x.CreationTime,
                    Username= x.Author.UserName,
                    Raiting=
                        db.ForumPostVotes.Count(y => y.Post.Id == x.Id && y.IsUpVote) -
                        db.ForumPostVotes.Count(y => y.Post.Id == x.Id && !y.IsUpVote)

                });
            var UpVotesCount=0;
            var DownVotesCount=0;

            //Pass model to view
            //Show forum post

            return View(latestForumPosts);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
